package cn.slipi.common.handler;

import cn.slipi.common.enums.ResponseCode;
import cn.slipi.common.exception.BizException;
import cn.slipi.common.response.ErrorResponse;
import cn.slipi.common.response.builder.ResponseBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class BizExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        if (e instanceof BizException) {
            response.setStatus(ResponseCode.BIZ_ERROR.code());
            BizException bizException = (BizException) e;
            ErrorResponse error = ErrorResponse.error(ResponseCode.BIZ_ERROR, e, bizException.getMsg());
            log.warn("URL:{},{}！", request.getRequestURI(), ResponseCode.BIZ_ERROR.msg(), e);
            return ResponseBuilder.build(error);
        }
        return null;
    }
}
